import React, { Component } from 'react'
import PubSub from 'pubsub-js'
import './index.css'

export default class List extends Component {
	//初始化状态
	state = {
		isFirst:true, //是否初次显示
		isLoading:false, //是否处于加载中
		users:[], //用户列表
		isError:false//请求是否出错
	}
	render() {
		const {isFirst,isLoading,users,isError} = this.state
		return (
			<div className="row">
				{
					isFirst ? <h2>欢迎使用！</h2> : 
					isLoading ? <h2>加载中.....</h2> : 
					isError ? <h2>阿偶，请求出错了</h2> :
					users.map((userObj)=>{
						return (
							<div className="card" key={userObj.login}>
								<a href={userObj.html_url} target="_blank" rel="noreferrer">
									<img src={userObj.avatar_url} alt="atguigu" style={{width: '100px'}}/>
								</a>
								<p className="card-text">{userObj.login}</p>
							</div>
						)
					})
				}
			</div>
		)
	}
	componentDidMount(){
		//订阅消息，用于接收用户列表
		this.pid = PubSub.subscribe('getData',(_,data)=>{
			console.log('List组件收到了数据',data)
			//更新数据
			this.setState({...this.state,...data})
		})
	}
	componentWillUnmount(){
		//取消订阅
		PubSub.unsubscribe(this.pid)
	}
}
